import hashlib
import os
import base64


def set_password(passwd) -> str:
    salt = os.urandom(9)
    hashed = hash_password(passwd, salt)
    hashed = base64.b64encode(hashed).decode("utf-8")
    salt = base64.b64encode(salt).decode("utf-8")
    return f"{hashed}${salt}"


def hash_password(passwd, salt) -> bytes:
    digest = hashlib.sha1()
    digest.update(passwd.encode("utf-8"))
    digest.update(salt)
    return digest.digest()


def check_passwd(passwd, hashed_passwd):
    hashed, salt = hashed_passwd.split("$")
    hashed, salt = base64.b64decode(hashed), base64.b64decode(salt)
    return hashed == hash_password(passwd, salt)


passwd = "密码123"
hashed = set_password(passwd)

print("passwd: ", passwd)
print("hashed: ", hashed)
print(" check: ", check_passwd(passwd, hashed))
